package project.sample.protocol.http;


import java.util.List;
import java.util.Objects;

/**
 * @author: WUZH009
 * @date: 2019/8/21 17:23
 **/
public class DefaultHttpResponse implements HttpResponse {

    private byte[] body;
    private List<HttpHeader> headers;
    private int status;

    public DefaultHttpResponse(List<HttpHeader> headers, int status) {
        Objects.requireNonNull(headers);
        this.headers = headers;
        this.status = status;
    }

    @Override
    public byte[] bytes() {
        StringBuilder all = new StringBuilder();
        all.append("HTTP/1.1 ").append(status).append("\n");
        for (HttpHeader header : headers) {
            all.append(header.getName()).append(": ").append(header.getValues()[0]).append("\n");
        }
        all.append("\n").append(new String(body)).append("\n");
        return all.toString().getBytes();
    }

    @Override
    public List<HttpHeader> headers() {
        return headers;
    }

    @Override
    public void addHeader(String name, String value) {
        if (name == null || "".equals(name)) {
            return;
        }
        for (HttpHeader header : headers) {
            if (name.equals(header.getName())) {
                return;
            }
        }
        headers.add(new HttpHeader(name, new String[]{value}));

    }

    @Override
    public void setHeader(String name, String value) {
        if (name == null || "".equals(name)) {
            return;
        }
        for (int i = 0; i < headers.size(); i++) {
            HttpHeader header = headers.get(i);
            if (name.equals(header.getName())) {
                headers.set(i, new HttpHeader(name, new String[]{value}));
                return;
            }
        }
        headers.add(new HttpHeader(name, new String[]{value}));

    }

    @Override
    public int status() {
        return status;
    }

    @Override
    public void body(byte[] body) {
        this.body = body;
    }
}
